package com.hexus.eve.actions;

import java.util.List;
import java.util.ResourceBundle;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hexus.eve.entities.Account;
import com.hexus.eve.entities.security.User;
import com.hexus.eve.utils.CurrentUser;
import com.hexus.eve.utils.EmptyItems;
import com.opensymphony.xwork2.ActionSupport;

public class DisplayAccount extends ActionSupport{

	private static final long serialVersionUID = 1L;

	@Autowired
	SessionFactory sessionFactory;
	
	private Integer id = EmptyItems.INTEGER;
	private Integer edit = 0;
	private Account account;
	private Boolean valid = false;
	private String newApiKey = EmptyItems.STRING;
	private Integer newUserId = EmptyItems.INTEGER;
	 
	
	public String execute() {
		if(id != -1) { // id is defined
			User user = CurrentUser.getUser();
			List<Account> accounts = user.getAccounts();
			for(Account a: accounts) {
				if(a.getId().intValue() == id) {
					account = a;
					
					//These variables are for edit mode text input fields
					newApiKey = a.getMaskedApiKey();
					newUserId = a.getUserId();

					if(!a.isSynchronizationUpToDate()) {
						a.synchronizeWithEve(sessionFactory);
					} else //synchronization includes availability status check, thus there is no need to do this twice  
						if(!a.isAvailabilityStatusUpToDate()) {
							a.updateAvailabilityStatus();
						}

					return SUCCESS;
				}
			}
			ResourceBundle bundle = ResourceBundle.getBundle ("global", getLocale());
			addActionError(bundle.getString("validation.cant.find.record"));
		}
		return SUCCESS;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
	
	public Integer getEdit() {
		return edit;
	}

	public void setEdit(String edit) {
		if(edit != null && !"".equals(edit))
			this.edit = Integer.parseInt(edit);
	}
	
	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public Boolean getValid() {
		return valid;
	}

	public void setValid(Boolean valid) {
		this.valid = valid;
	}
	public String getNewApiKey() {
		return newApiKey;
	}
	public void setNewApiKey(String newApiKey) {
		this.newApiKey = newApiKey;
	}
	public Integer getNewUserId() {
		return newUserId;
	}
	public void setNewUserId(String newUserId) {
		try {
			this.newUserId = Integer.parseInt(newUserId);
		} catch (NumberFormatException e) {
		}
	}
/*
	public List getCharacters() {
		return characters;
	}

	public void setCharacters(List characters) {
		this.characters = characters;
	}
*/
}
